package com.studyweb.controller;

import com.studyweb.pojo.entity.Achievement;
import com.studyweb.pojo.entity.UserAchievement;
import com.studyweb.service.AchievementService;
import com.studyweb.service.UserAchievementService;
import com.studyweb.pojo.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 成就控制器
 * 
 * @author StudyWeb Team
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/api/achievement")
public class AchievementController {

    @Autowired
    private AchievementService achievementService;
    
    @Autowired
    private UserAchievementService userAchievementService;

    /**
     * 获取所有成就（分页）
     * 
     * @param page 页码
     * @param size 每页大小
     * @param name 成就名称（可选）
     * @param category 成就类别（可选）
     * @return 成就列表
     */
    @GetMapping("/list")
    public Result listAll(@RequestParam(defaultValue = "1") int page,
                          @RequestParam(defaultValue = "10") int size,
                          @RequestParam(required = false) String name,
                          @RequestParam(required = false) String category) {
        try {
            List<Achievement> achievements = achievementService.listByPage(page, size, name, category);
            int total = achievementService.count(name, category);
            
            Map<String, Object> data = new HashMap<>();
            data.put("list", achievements);
            data.put("total", total);
            data.put("page", page);
            data.put("size", size);
            
            return Result.success(data);
        } catch (Exception e) {
            log.error("获取成就列表异常", e);
            return Result.error("获取成就列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据类别获取成就
     * 
     * @param category 成就类别
     * @return 成就列表
     */
    @GetMapping("/list/category/{category}")
    public Result listByCategory(@PathVariable String category) {
        try {
            List<Achievement> achievements = achievementService.listByCategory(category);
            return Result.success(achievements);
        } catch (Exception e) {
            log.error("获取成就列表异常", e);
            return Result.error("获取成就列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户成就
     * 
     * @param request HTTP请求
     * @return 用户成就列表
     */
    @GetMapping("/user")
    public Result getUserAchievements(HttpServletRequest request) {
        try {
            // 从请求属性中获取用户ID（由JWT拦截器设置）
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("未登录或登录已过期");
            }
            
            List<UserAchievement> userAchievements = userAchievementService.listByUserId(userId);
            
            // 获取成就统计信息
            int totalCount = userAchievementService.countByUserId(userId);
            int checkinCount = userAchievementService.countByUserIdAndCategory(userId, "签到");
            
            Map<String, Object> data = new HashMap<>();
            data.put("achievements", userAchievements);
            data.put("totalCount", totalCount);
            data.put("checkinCount", checkinCount);
            
            return Result.success(data);
        } catch (Exception e) {
            log.error("获取用户成就异常", e);
            return Result.error("获取用户成就失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户特定类别的成就
     * 
     * @param request HTTP请求
     * @param category 成就类别
     * @return 用户成就列表
     */
    @GetMapping("/user/category/{category}")
    public Result getUserAchievementsByCategory(HttpServletRequest request, @PathVariable String category) {
        try {
            // 从请求属性中获取用户ID（由JWT拦截器设置）
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("未登录或登录已过期");
            }
            
            List<UserAchievement> userAchievements = userAchievementService.listByUserIdAndCategory(userId, category);
            return Result.success(userAchievements);
        } catch (Exception e) {
            log.error("获取用户成就异常", e);
            return Result.error("获取用户成就失败：" + e.getMessage());
        }
    }

    /**
     * 更新用户成就显示状态
     * 
     * @param request HTTP请求
     * @param id 用户成就ID
     * @param isDisplayed 是否显示
     * @return 更新结果
     */
    @PutMapping("/user/{id}/display/{isDisplayed}")
    public Result updateDisplayStatus(HttpServletRequest request, @PathVariable Long id, @PathVariable boolean isDisplayed) {
        try {
            // 从请求属性中获取用户ID（由JWT拦截器设置）
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("未登录或登录已过期");
            }
            
            // 验证该成就是否属于当前用户
            UserAchievement userAchievement = userAchievementService.getById(id);
            if (userAchievement == null || !userAchievement.getUserId().equals(userId)) {
                return Result.error("无权操作该成就");
            }
            
            boolean success = userAchievementService.updateDisplayStatus(id, isDisplayed);
            if (success) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            log.error("更新用户成就显示状态异常", e);
            return Result.error("更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 领取成就积分奖励
     * 
     * @param request HTTP请求
     * @param id 用户成就ID
     * @return 领取结果
     */
    @PostMapping("/user/{id}/claim")
    public Result claimAchievementPoints(HttpServletRequest request, @PathVariable Long id) {
        try {
            // 从请求属性中获取用户ID（由JWT拦截器设置）
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("未登录或登录已过期");
            }
            
            // 领取成就积分
            boolean success = userAchievementService.claimAchievementPoints(id, userId);
            if (success) {
                // 获取用户最新积分
                int userPoints = userAchievementService.getUserPoints(userId);
                Map<String, Object> result = new HashMap<>();
                result.put("message", "积分领取成功");
                result.put("points", userPoints);
                return Result.success(result);
            } else {
                return Result.error("积分领取失败");
            }
        } catch (Exception e) {
            log.error("领取成就积分异常", e);
            return Result.error("领取失败：" + e.getMessage());
        }
    }
    
    /**
     * 添加成就
     * 
     * @param achievement 成就信息
     * @return 添加结果
     */
    @PostMapping("/admin")
    public Result addAchievement(@RequestBody Achievement achievement) {
        try {
            Long achievementId = achievementService.add(achievement);
            Map<String, Object> result = new HashMap<>();
            result.put("achievementId", achievementId);
            result.put("message", "成就添加成功");
            return Result.success(result);
        } catch (Exception e) {
            log.error("添加成就异常", e);
            return Result.error("添加成就失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新成就
     * 
     * @param achievementId 成就ID
     * @param achievement 成就信息
     * @return 更新结果
     */
    @PutMapping("/admin/{achievementId}")
    public Result updateAchievement(@PathVariable Long achievementId, @RequestBody Achievement achievement) {
        try {
            achievement.setAchievementId(achievementId);
            boolean success = achievementService.update(achievement);
            if (success) {
                return Result.success("成就更新成功");
            } else {
                return Result.error("成就更新失败");
            }
        } catch (Exception e) {
            log.error("更新成就异常", e);
            return Result.error("更新成就失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除成就
     * 
     * @param achievementId 成就ID
     * @return 删除结果
     */
    @DeleteMapping("/admin/{achievementId}")
    public Result deleteAchievement(@PathVariable Long achievementId) {
        try {
            boolean success = achievementService.delete(achievementId);
            if (success) {
                return Result.success("成就删除成功");
            } else {
                return Result.error("成就删除失败");
            }
        } catch (Exception e) {
            log.error("删除成就异常", e);
            return Result.error("删除成就失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID获取成就详情
     * 
     * @param achievementId 成就ID
     * @return 成就详情
     */
    @GetMapping("/admin/{achievementId}")
    public Result getAchievementById(@PathVariable Long achievementId) {
        try {
            Achievement achievement = achievementService.getById(achievementId);
            if (achievement != null) {
                return Result.success(achievement);
            } else {
                return Result.error("成就不存在");
            }
        } catch (Exception e) {
            log.error("获取成就详情异常", e);
            return Result.error("获取成就详情失败：" + e.getMessage());
        }
    }
}